﻿using System;
using System.IO;
using System.Web.UI;
using VitCode.Castle.Helper;

namespace CRS.Web.UserControls
{
    public partial class ImageSettingCtl : UserControl
    {
        public string PicDirPath
        {
            get
            {
                var obj = ViewState["PicDirPath"] ?? "";
                return obj.ToString();
            }
            set { ViewState["PicDirPath"] = value; }
        }

        public string Text
        {
            get
            {
                if (!string.IsNullOrEmpty(upImage.FileName.Trim()))
                    return PicDirPath + upImage.FileName;
                return ImagePath;
            }
            set
            {
                if (value != "")
                    Image1.ImageUrl = value;
                return;
            }
        }

        private string ImagePath
        {
            get
            {
                if (ViewState["ImagePath"] != null)
                    return ViewState["ImagePath"].ToString();
                return "";
            }
            set { ViewState["ImagePath"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Operator"] != null)
            {
                if (Session["Operator"].ToString() != "Add")
                {
                    Image1.Visible = true;

                    ImagePath = Image1.ImageUrl;
                    Session["Operator"] = null;
                }
            }
        }

        protected void button1_Click(object sender, EventArgs e)
        {
            if (upImage.HasFile)
            {
                if (CheckFileType(upImage.FileName))
                {
                    string filePath = PicDirPath + upImage.FileName;
                    upImage.SaveAs(MapPath(filePath));
                    Image1.Visible = true;
                    Image1.ImageUrl = filePath;
                    ImagePath = filePath;
                    Alert.MessageBox("上传成功！");
                }
                else
                {
                    Alert.MessageBox("非法的图片文件！");
                }
            }
        }

        private bool CheckFileType(string fileName)
        {
            string strExt = Path.GetExtension(fileName);
            switch (strExt.ToLower())
            {
                case ".gif":
                    return true;
                case ".jpg":
                    return true;
                case ".jpeg":
                    return true;
                case ".png":
                    return true;
                default:
                    return false;
            }
        }
    }
}
